﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using UncleBobWebService.Models;
using UncleBobWebService.ServiceRequester;
using UncleBobApplicantWebService.ApplicantWebService;


namespace UncleBobApplicantWebService.Controllers
{
    public class RegisterController : Controller
    {
        private UncleBobApplicantWebService.ApplicantWebService.WebServiceClient mApplicantClient = 
            new UncleBobApplicantWebService.ApplicantWebService.WebServiceClient();


        //**************************************************
        //Display register view
        //**************************************************
        public ActionResult Register()
        {
            if (null == TempData[SessionKeys.USER])
            {
                RegisterModel applicant = new RegisterModel();
                Session[SessionKeys.USER] = applicant;
                Session["NewReg"] = true;
                return View(applicant);
            }
            else
            {
                return View(TempData[SessionKeys.USER] as RegisterModel);
            }
        }

        public ActionResult EditRegistration()
        {
            RegisterModel applicant = Session[SessionKeys.USER] as RegisterModel;
            Session["NewReg"] = false;
            TempData[SessionKeys.USER] = applicant;
            return RedirectToAction("Register", "Register");
        }

        //**************************************************
        //Display preview view
        //**************************************************
        public ActionResult RegisterPreview()
        {
            return View(Session[SessionKeys.USER]);
        }


        //**************************************************
        //Form action handle
        //**************************************************
        [SessionExpiredFilter]
        public ActionResult FormAction(RegisterModel model, FormCollection collection)
        {
            bool newReg = (bool)Session["newReg"];

            if (null != collection["cancel"] && newReg)
            {
                return RedirectToAction("Index", "Welcome");
            }
            else if (null != collection["cancel"] && !newReg)
            {
                return RedirectToAction("MainMenu", "ApplicantMainMenu");
            }
            else
            {
                RegisterModel applicant = Session[SessionKeys.USER] as RegisterModel;

                applicant.Username = collection["txtName"];
                applicant.Password = collection["txtPWord"];
                applicant.FirstName = collection["txtFirstN"];
                applicant.LastName = collection["txtLastN"];
                applicant.MI = collection["txtMiddle"];
                applicant.PhoneNumber = collection["txtPhone"];
                applicant.Email = collection["txtEmail"];
                applicant.Address = collection["txtAddress"];

                Session[SessionKeys.USER] = applicant;
            }

            return RedirectToAction("RegisterPreview", "Register");
        }

        [SessionExpiredFilter]
        public ActionResult PreviewFormAction(FormCollection collection)
        {
            if (null != collection["cancel"])
            {
                return RedirectToAction("Index", "Welcome");
            }
            else if (null != collection["back"])
            {
                return RedirectToAction("Register", "Register");
            }
            else
            {
                RegisterModel applicant = Session[SessionKeys.USER] as RegisterModel;
                Message msg = new Message();
                bool newReg = (bool)Session["NewReg"];
                bool result = false;
                
                // Make sure that user registration is valid before storing in DB
                if (!newReg)
                {
                    msg = new Message(MessageTypes.SERVICE_EDIT_REGISTRATION);
                    msg.Data = applicant;
                    msg = mApplicantClient.RequestService(msg);

                    if (!msg.Result)
                    {
                        TempData[SessionKeys.ERROR] = string.Format("Problem editing registration information.",
                        applicant.Username);

                        return RedirectToAction("Error", "Error");
                    }
                }
                else
                {
                    RegisterNewUser(applicant);
                }

                return RedirectToAction("Index", "Welcome");                
            }
        }

        private bool UserAlreadyRegistered(RegisterModel applicant)
        {
            Message msg = new Message();
            WebServiceClient appClient = new WebServiceClient();

            // VALIDATE_USER message type should be changed to look only for same USERNAME -
            // currently it is validating that every field for a particular user is the same,
            // which is not what we want at all.
            msg.Category = MessageTypes.SERVICE_VALIDATE_USER; 
            msg.Data = applicant;

            //
            // UNDEFINED BEHAVIOR !!!! (I think)
            // ------------------------------------------------------------
            // This msg seems seriously borked -- sometimes it will return 
            // an object in the data field, other times it will return NULL 
            // in the data field, even when looking for SAME object in DB.
            // In any case, I cannot reproduce reliable, consistent behavior
            // when calling this message. What is the intent? Is it supposed
            // to return NULL if the object is found? Or is it supposed to 
            // return an object with a boolean in the .Result field? Please
            // look into fixing this.
            //
            msg = appClient.RequestService(msg); 

            return msg.Result;
        }

        private bool RegisterNewUser(RegisterModel applicant)
        {
            Message msg = new Message();
            msg.Category = MessageTypes.SERVICE_REGISTER_NEW_USER;
            msg.Data = applicant as object;
            msg = mApplicantClient.RequestService(msg);
            return msg.Result;
        }

        private void DeleteExistingRegistration(RegisterModel applicant)
        {
            Message msg = new Message();
            msg.Category = MessageTypes.SERVICE_GET_REGISTERED_USER;
            msg.Data = applicant;
            msg = mApplicantClient.RequestService(msg);

            if (null != msg)
            {
                msg.Category = MessageTypes.SERVICE_DELETE_REGISTERED_USER;
                msg = mApplicantClient.RequestService(msg);
            }
        }
    }
}
